<script setup lang="ts">
import { ref, computed } from 'vue'
import CategoryModel from '@/models/CategoryModel'
import { chain } from 'lodash'
import useApi from '@/core/apiStore'

const apiStore = useApi()

const props = defineProps({
  saveCallback: {
    type: Function,
    required: true,
    validator: (value: Function) => typeof value === 'function',
  },
})

const visible = ref(false)
const isEditing = ref(false)
const formData = ref<CategoryModel>(CategoryModel.createDefault())

const computedConditions = computed(() => {
  const _keys = chain(apiStore.apiStates.getCondtions.data)
    .keys()
    .map(key => ({ label: key, value: key }))
    .value()
  console.log('keys', _keys)
  return _keys
})

const computedIps = computed(() => {
  return chain(apiStore.apiStates.getNodes.data)
    .map(row => ({ label: row.ip, value: row.ip }))
    .value()
})

const show = (category?: CategoryModel) => {
  isEditing.value = category !== undefined
  if (category) {
    formData.value = category
  } else {
    formData.value = CategoryModel.createDefault()
  }
  visible.value = true
}

const handleSave = async () => {
  const shouldClose = await props.saveCallback(formData.value)
  if (shouldClose) {
    visible.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}

defineExpose({
  show,
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="isEditing ? '编辑集群' : '新增集群'"
    width="50%"
  >
    <el-form :model="formData" label-width="120px">
      <el-form-item label="集群名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="告警条件">
        <el-select
          v-model="formData.warningConditions"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="告警条件，可多选"
          style="width: 100%"
        >
          <el-option
            v-for="item in computedConditions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="节点IPs">
        <el-select
          v-model="formData.ips"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="ip，可多选"
          style="width: 100%"
        >
          <el-option
            v-for="item in computedIps"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
